package cn.kgc.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.kgc.entity.DataDictionary;
import cn.kgc.form.DataDictionaryForm;
import cn.kgc.form.DictItemQueryForm;
import cn.kgc.grace.result.GraceJSONResult;
import cn.kgc.interceptor.JwtInterceptor;
import cn.kgc.service.DataDictionaryService;
import cn.kgc.utils.PagedGridResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @author YC
 */
@RestController
@RequestMapping("/dataDictionary")
@Api(tags = "数据字典表模块")
@Validated
@Slf4j
@CrossOrigin
public class DataDictionaryController {

    @Resource
    private DataDictionaryService dataDictionaryService;

    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 使用线程池异步编排-查询数据字典表
     *
     * @param form 数据字典表单
     * @return 数据字典表
     */
    @PostMapping("/admin/getItemsByKeys")
    @ApiOperation("使用线程池异步编排-查询数据字典表")
    public GraceJSONResult getItemsByKeys(@RequestBody DictItemQueryForm form) {

        CompletableFuture<List<DataDictionary>> future1 = CompletableFuture.supplyAsync(() -> {
            //根据公司优势的key 获得数据字典值
            return dataDictionaryService.queryDataDictionaryByItemKey(form.getAdvantages());
        }, threadPoolTaskExecutor);
        CompletableFuture<List<DataDictionary>> future2 = CompletableFuture.supplyAsync(() -> {
            // 根据福利待遇key 获得数据字典值
            return dataDictionaryService.queryDataDictionaryByItemKey(form.getBenefits());
        }, threadPoolTaskExecutor);
        CompletableFuture<List<DataDictionary>> future3 = CompletableFuture.supplyAsync(() -> {
            // 根据薪资福利key 获得数据字典值
            return dataDictionaryService.queryDataDictionaryByItemKey(form.getBonus());
        }, threadPoolTaskExecutor);
        CompletableFuture<List<DataDictionary>> future4 = CompletableFuture.supplyAsync(() -> {
            // 根据补助津贴key 获得数据字典值
            return dataDictionaryService.queryDataDictionaryByItemKey(form.getSubsidy());
        }, threadPoolTaskExecutor);
        // 等待四个异步任务执行完成
        CompletableFuture.allOf(future1, future2, future3, future4).join();
        Map<String, List<DataDictionary>> map = new HashMap<>(4);
        try {
            map.put("advantages", future1.get());
            map.put("benefits", future2.get());
            map.put("bonus", future3.get());
            map.put("subsidies", future4.get());
        } catch (Exception e) {
            return GraceJSONResult.errorMsg("查询公司福利（数据字典）失败");
        }
        return GraceJSONResult.ok(map);

    }


    @PostMapping("/app/getDataByCode")
    @ApiOperation(value = "根据字典编码查询字典项")
    public GraceJSONResult getDataByCode(String typeCode) {
        String userId = JwtInterceptor.userIds.get();
        if (StrUtil.isNotBlank(userId)) {
            return GraceJSONResult.ok(
                    dataDictionaryService.queryDataDictionaryByType(typeCode)
            );
        }
        return GraceJSONResult.errorMsg("您没有权限操作!");
    }

    @PostMapping("/admin/delete")
    @ApiOperation(value = "删除数据字典项")
    public GraceJSONResult delete(String id) {
        String adminUserId = JwtInterceptor.adminUserIds.get();
        if (StrUtil.isNotBlank(adminUserId)) {
            return GraceJSONResult.ok(dataDictionaryService.deleteById(id));
        }
        return GraceJSONResult.errorMsg("您没有权限操作");
    }

    @PostMapping("/admin/isEnable")
    @ApiOperation(value = "数据字典项的启用和禁用")
    public GraceJSONResult isEnable(String id) {
        String adminUserId = JwtInterceptor.adminUserIds.get();
        if (StrUtil.isNotBlank(adminUserId)) {
            //获得原来的数据
            DataDictionary dataDictionary = dataDictionaryService.getById(id);
            //如果原来是请用就改为禁用。如果是禁用改为启用。
            int enable = dataDictionary.getEnable() == 1 ? 0 : 1;
            dataDictionary.setEnable((short) enable);
            //更新数据
            dataDictionaryService.updateById(dataDictionary);
            //返回数据
            return GraceJSONResult.ok(dataDictionary);
        }
        return GraceJSONResult.errorMsg("您没有权限操作");
    }


    @PostMapping("/admin/save")
    @ApiOperation(value = "新增数据字典项")
    public GraceJSONResult save(DataDictionaryForm dataDictionaryForm) {
        String adminUserId = JwtInterceptor.adminUserIds.get();
        if (StrUtil.isNotBlank(adminUserId)) {
            DataDictionary dataDictionary = new DataDictionary();
            BeanUtil.copyProperties(dataDictionaryForm, dataDictionary);
            return GraceJSONResult.ok(dataDictionaryService.save(dataDictionary));
        }
        return GraceJSONResult.errorMsg("您没有权限操作");
    }

    @PostMapping("/admin/list")
    @ApiOperation(value = "按条件分页查询字典信息")
    public PagedGridResult list(
            @RequestParam(defaultValue = "") String typeName,
            @RequestParam(defaultValue = "") String itemKey,
            @RequestParam(defaultValue = "1") int pageIndex,
            @RequestParam(defaultValue = "10") int pageSize) {
        String adminUserId = JwtInterceptor.adminUserIds.get();
        if (StrUtil.isNotBlank(adminUserId)) {
            return dataDictionaryService.page(pageIndex, pageSize, typeName, itemKey);
        }
        //如果登录的用户不是后台管理员,返回空的集合
        return new PagedGridResult();
    }
}